<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :search.sync="search"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
    >
      <!--      <template slot="menuRight">-->
      <!--        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val)"></user-table-config>-->
      <!--      </template>-->
      <template slot="menuLeft">
        <el-button type="warning" size="small" icon="el-icon-download" @click="handleExport">导出</el-button>
      </template>
    </avue-crud>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows"></common-modal-template>
    <export-comp
      ref="exportComp"
      page-api-url="mes-abacus/qms-statistic/workorder-ng-info"
      :option="exportOption"
      :page="page"
      :query="exportParams"
      file-name="不良统计报表"
    ></export-comp>
  </basic-container>
</template>

<script>
import { getList } from '@/api/report/productFailureStatistics';
import { mapGetters } from 'vuex';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';
import exportComp from '@/components/export-comp';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
export default {
  name: 'productFailureStatistics',
  components: {
    exportComp,
    userTableConfig,
    CommonModalTemplate
  },
  mixins: [userConfig()],
  data() {
    return {
      form: {},
      query: {},
      search: {},
      exportParams: {},
      loading: false,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      exportOption: {
        column: [
          {
            label: '时间范围',
            prop: 'dateRange'
          },
          {
            label: '工单号',
            prop: 'workOrderNo'
          },
          {
            label: '产品型号',
            prop: 'partModel'
          },
          {
            label: '生产数',
            prop: 'completedQuantity'
          },
          {
            label: '不良总数',
            prop: 'totalNgQuantity'
          },
          {
            label: '总不良率',
            prop: 'totalNgRate'
          },
          {
            label: '合格率',
            prop: 'passRate'
          },
          {
            label: '不良现象',
            prop: 'ngPhenomenon'
          },
          {
            label: '不良原因',
            prop: 'ngCause'
          },
          {
            label: '不良数',
            prop: 'ngQuantity'
          },
          {
            label: '不良率',
            prop: 'ngRate'
          }
        ]
      },
      option: {
        height: 'calc(100vh - 438px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 4,
        searchMenuPosition: 'right',
        searchLabelWidth: 100,
        labelWidth: 120,
        menu: false,
        menuWidth: 100,
        border: true,
        index: true,
        indexLabel: '序号',
        viewBtn: false,
        addBtn: false,
        delBtn: false,
        editBtn: false,
        selection: false,
        columnBtn: false,
        dialogClickModal: false,
        column: [
          {
            label: '日期',
            width: 150,
            span: 12,
            prop: 'createTime',
            type: 'datetime',
            searchType: 'datetimerange',
            search: true,
            searchOrder: 2,
            searchLabel: '时间范围',
            searchSpan: 8,
            searchFormat: 'yyyy-MM-dd HH:mm:ss',
            searchValueFormat: 'yyyy-MM-dd HH:mm:ss',
            startPlaceholder: '开始时间',
            endPlaceholder: '结束时间',
            hide: true
          },
          {
            label: '工单号',
            prop: 'workOrderNo',
            search: true,
            type: 'search',
            searchOrder: 1,
            appendClick: () => {
              this.openWorkOrderNoModal();
            },
            searchRules: [
              {
                required: true,
                message: '请输入选择工单号',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '产品型号',
            prop: 'partModel'
          },
          {
            label: '生产数',
            prop: 'completedQuantity'
          },
          {
            label: '不良总数',
            prop: 'totalNgQuantity'
          },
          {
            label: '总不良率',
            prop: 'totalNgRate'
          },
          {
            label: '合格率',
            prop: 'passRate'
          },
          {
            label: '不良现象',
            prop: 'ngPhenomenon'
          },
          {
            label: '不良原因',
            prop: 'ngCause'
          },
          {
            label: '不良数',
            prop: 'ngQuantity'
          },
          {
            label: '不良率',
            prop: 'ngRate'
          }
        ]
      },
      data: [],
      tableOption: {}
    };
  },
  computed: {
    ...mapGetters(['permission']),
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  created() {},
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  methods: {
    searchReset() {
      this.query = {};
      this.search = {};
      this.data = [];
      // this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      if (this.search.createTime.length > 0) {
        params.startDate = this.$moment(this.search.createTime[0]).format('YYYY-MM-DD HH:mm:ss');
        params.endDate = this.$moment(this.search.createTime[1]).format('YYYY-MM-DD HH:mm:ss');
        delete this.query.createTime;
      }
      params.workOrderNo = this.search.workOrderNo;
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },

    handleDownload(link) {
      window.open(`${link}`);
    },
    openPreview(index = 0, link) {
      this.$ImagePreview([{ url: link }], index, {
        closeOnClickModal: false
      });
    },
    handleExport() {
      this.exportParams = this.getExportParam();
      this.$refs.exportComp.visible = true;
    },
    getExportParam() {
      const exportParams = this._cloneDeep(this.search);
      if (exportParams.createTime.length > 0) {
        exportParams.startDate = this.$moment(exportParams.createTime[0]).format('YYYY-MM-DD HH:mm:ss');
        exportParams.endDate = this.$moment(exportParams.createTime[1]).format('YYYY-MM-DD HH:mm:ss');
      }
      delete exportParams.createTime;
      return exportParams;
    },
    /**
     * 打开选择工单号模态框
     */
    openWorkOrderNoModal() {
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择工单号（双击进行选择）',
        url: '/api/mes-product/work-order/page?workOrderStatus=2,3',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '生产订单',
            prop: 'productionOrderNo',
            search: true
          },
          {
            label: '生产工单',
            prop: 'orderNo',
            search: true
          },
          {
            label: '工单类型',
            prop: 'orderType',
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=order_type',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
          },
          {
            label: '工单数量',
            prop: 'planQuantity'
          },
          {
            label: '产品编码',
            prop: 'partNo',
            search: true
          },
          {
            label: '产品名称',
            prop: 'partName'
          },
          {
            label: 'BOM版本',
            prop: 'bomVersion'
          },
          {
            label: '派工产线',
            prop: 'productionLineName'
          },
          {
            label: '计划开始时间',
            prop: 'planStartDate'
          },
          {
            label: '计划结束时间',
            prop: 'planEndDate'
          },
          {
            label: '制定人',
            prop: 'creatorName'
          },
          {
            label: '状态',
            prop: 'status',
            type: 'select',
            dicData: [
              {
                label: '待排程',
                value: 1
              },
              {
                label: '待生产',
                value: 2
              },
              {
                label: '生产中',
                value: 3
              },
              {
                label: '完工',
                value: 4
              },
              {
                label: '锁定',
                value: 5
              },
              {
                label: '强制完工',
                value: 6
              }
            ]
          },
          {
            label: '备注',
            prop: 'remark'
          }
        ]
      };
    },
    /**
     * 获取选中工单号
     */
    getSelectedRows(rowData) {
      this.search.workOrderNo = this._get(rowData, 'orderNo', '');
      // this.search.workOrderId = this._get(rowData, 'id', '');
      this.onLoad(this.page);
    }
  }
};
</script>

<style scoped></style>
